package com.wnxy.mallserver.controller;

import com.wnxy.mallserver.entity.User;
import com.wnxy.mallserver.response.Message;
import com.wnxy.mallserver.response.ResponseResult;
import com.wnxy.mallserver.response.StateCode;
import com.wnxy.mallserver.service.UserService;
import com.wnxy.mallserver.util.JWTUtil;
import com.wnxy.mallserver.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
//    redis注入
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 普通数据通过return返回
     * token通过响应头返回
     */
    @PostMapping("/login")
    public ResponseResult<User> login(@RequestBody LoginVo loginVo, HttpServletResponse response) {
        log.debug(loginVo.toString());
        /**登录逻辑*/

        //登录查询：登录错误会抛异常，运行就终止了，不会执行下面的代码
        User user = userService.login(loginVo);
        //1.登陆成功，颁发令牌
        String token = JWTUtil.generateToken(user.getId(),user.getAccount());
        //2.设置响应头   authorization:权限.大小写都可以，但是在浏览器中的是小写，所以此处还是建议小写
        response.setHeader("authorization", token);
        //3.暴露标头，告诉浏览器别过滤这个头，让前端程序能够拿到该标头
        response.setHeader("Access-Control-Expose-Headers","authorization");
//        将token放入Redis，用于同前端返回的token进行比较
        redisTemplate.opsForValue().set(token,"");

        //封装数据并返回
        return new ResponseResult<>(StateCode.SUCCESS, Message.LOGIN_SUCCESS,user);

    }


}

